<template>
  <div class="total-out-consume">
    <div class="total-out-consume-top">
      <bordCharts
        :key="tablePieKey"
        :title="`${system}总产出与能耗`"
        :dataList="dataList"
        :requestData="requestData"
        :tableColumns="tableColumns"
        :width="1300"
        :height="290"
        :options="bordChartsOptions"
      />
    </div>
    <div class="total-out-consume-bottom">
      <linesCharts :key="tableLineKey" title="耗能费用趋势" :width="1300" :height="350" :options="trendOptions" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, computed, markRaw, getCurrentInstance } from "vue";
import linesCharts from "./linesCharts.vue";
import bordCharts from "./bordCharts.vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { viewConsumeTotal } from "@/api/energy/consumeCost";

interface Props {
  system?: string;
  activeName?: string;
  queryData?: Object | null;
}

interface Emits {
  (event: "request-data"): void;
}

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const emits = defineEmits<Emits>();

const props = withDefaults(defineProps<Props>(), {
  system: "系统",
  activeName: ""
});

const dataList = ref([
  {
    name: "电",
    icon: "icon_electricity",
    unit: "kwh"
  },
  {
    name: "水",
    icon: "icon_water",
    unit: "m³"
  },
  {
    name: "水",
    icon: "icon_water",
    unit: "m³"
  },
  {
    name: "水",
    icon: "icon_water",
    unit: "m³"
  },
  {
    name: "水",
    icon: "icon_water",
    unit: "m³"
  },
  {
    name: "水",
    icon: "icon_water",
    unit: "m³"
  }
]);

const requestData = ref<any>({});

const tableColumns = ref([
  // {
  //   type: "index",
  //   label: "序号",
  //   prop: "",
  //   width: "60",
  //   align: "center"
  // },
  {
    label: "能源",
    prop: "kind",
    width: "60",
    align: "left"
  },
  {
    label: "费用(万元)",
    prop: "cost",
    align: "left"
  },
  {
    label: "同比(%)",
    prop: "costYoy",
    align: "left"
  },
  {
    label: "环比(%)",
    prop: "costMom",
    align: "left"
  }
]);

const bordChartsOptions = ref<any>({});

const trendOptions = ref<any>({});

const tablePieKey = ref(Date.now());
const tableLineKey = ref(Date.now());

const getPageData = async val => {
  const param = Object.assign({}, val);
  const res: any = await viewConsumeTotal(param);
  dataList.value = res.costTable;
  requestData.value = res;
  bordChartsOptions.value = labelLayoutFn(res.costRatio || []);
  const obj: any = res;
  let seriesArr = [];
  let yaxisArr = [];
  const xData = obj.costTrend.xaxis || [];
  if (obj.costTrend.yaxis && obj.costTrend.yaxis.length > 0) {
    obj.costTrend.yaxis.forEach((item, index) => {
      seriesArr.push({
        name: item.name,
        type: item.name === "产出量" ? "line" : "bar",
        yAxisIndex: index,
        data: item.value.map(e => {
          return Number(Number(e).toFixed(2));
        }),
        emphasis: {
          focus: "series"
        }
      });
      yaxisArr.push({
        type: "value",
        name: item.name === "总费用" ? `${item.name}\n万元` : `${item.name}\nm³`,
        alignTicks: true,
        offset: index * 70,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1
          }
        }
      });
    });
  }
  trendOptions.value = labelLayoutTrendFn(xData, seriesArr, yaxisArr);
  tablePieKey.value = Date.now();
  tableLineKey.value = Date.now();
};

// 总排名
const labelLayoutAreaFn = async (ec: any) => {
  const title = "总排名";
  // const param = {
  //   level: queryParams.value.level,
  //   startDate: dateRange.value[0],
  //   endDate: dateRange.value[1],
  //   sysId: "",
  //   dimension: queryParams.value.queryTimeGranularity.split("")[0]
  // };
  // const res: any = await getConsumeCostOverView(param);
  // const data = res ? res.costRatio : [];
  const data = [];
  return labelLayoutFn(data);
};

const labelLayoutFn = (data: Array<dataType>) => {
  const options: UtilsEChartsOption = {
    color: ["#5B8FF9", "#5AD8A6 ", "#FFB910"],
    tooltip: {
      trigger: "item",
      formatter: `{a} <br/>{b}: {c} ({d}%)`
    },
    legend: {
      type: "scroll", // 设置图例分页类型为滚动
      icon: "rect",
      orient: "horizontal", // 水平排列
      right: "center", // 水平居中
      itemWidth: 20, // 图例标记的图形宽度
      itemHeight: 10, // 图例标记的图形高度
      selected: {},
      data: data.map(e => e.name) || []
    },
    grid: {
      left: "0px",
      top: "40px",
      right: "10px",
      bottom: "10px",
      containLabel: true
    },
    series: [
      {
        name: "系统总产出与能耗",
        type: "pie",
        label: {
          formatter: `{c|{c}} \n{d|{d}%}`,
          rich: {
            c: {
              fontSize: 16
            },
            d: {
              fontSize: 16,
              fontWeight: "bold"
            }
          }
        },
        radius: "50%",
        data: data || []
      }
    ]
  };
  return options;
};

const labelLayoutTrendFn = (xData, serisData, yAxis) => {
  const options: UtilsEChartsOption = {
    tooltip: {
      trigger: "axis"
    },
    legend: {
      type: "scroll", // 设置图例分页类型为滚动
      icon: "rect",
      orient: "horizontal", // 水平排列
      right: "center", // 水平居中
      itemWidth: 20, // 图例标记的图形宽度
      itemHeight: 10, // 图例标记的图形高度
      selected: {},
      data: serisData.map(e => e.name) || []
    },
    grid: {
      left: "24px",
      right: `${yAxis.length * 50}px`,
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: xData
    },
    yAxis: yAxis,
    series: serisData
  };
  return options;
};

watch(
  () => props,
  val => {
    if (Object.keys(props.queryData).length) {
      getPageData(props.queryData);
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.total-out-consume {
  display: flex;
  flex-flow: column nowrap;
  gap: 16px;
  min-width: 1300px;
  height: calc(100% - 136px);

  .total-out-consume-top {
    height: 290px;
  }

  .total-out-consume-bottom {
    height: 350px;
  }
}
</style>
